package LogBook;

import android.content.Context;
import android.content.ContentValues;
import android.database.sqlite.*;
import android.database.Cursor;
import LogBook.QSO;

public class Book extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION = 1;
	private static final String DATABASE_NAME = "LogBook";

	public Book(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS Logs ( "
				+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
				+ "CallSign CHAR(10), " + "Frequency int(8), "
				+ "Mode CHAR(3), " + "RST CHAR(7), " + "Date date) ";

		db.execSQL(CREATE_TABLE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS Logs");

		this.onCreate(db);
	}

	private static final String[] COLUMNS = { "CallSign", "Frequency", "Mode",
			"RST", "Date" };

	public void addQSO(QSO qso) {
		ContentValues values = new ContentValues();
		values.put("CallSign", qso.getCallSign());
		values.put("Frequency", qso.getFrequency());
		values.put("Mode", qso.getMode());
		values.put("RST", qso.getRST());
		values.put("Date", qso.getTime().toString());

		SQLiteDatabase db = this.getWritableDatabase();

		db.insert("Logs", null, values);
		db.close();
	}

	public void deleteQSO(int id) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.delete("Logs", "id = ?", new String[] { String.valueOf(id) });
		db.close();
	}
	
	public Cursor getQSOs(){
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor c = db.query("Logs", COLUMNS, DATABASE_NAME, null, null, null, null);
		db.close();
		return c;
	}
}
